package org.binge.widget.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by hiddenlogic on 16/6/1.
 */
public class SimpleExeclUtil {

    private static Logger logger = LoggerFactory.getLogger(SimpleExeclUtil.class);
    /** 默认从execl的第2行读取数据
     * @param inputStream  execl文件流
     * @param c  execl对应的javabean的class
     * @param fieldNames key值为execl第几(从0开始)列,value为该列对应于javabean中的filedName(将javabean与execl中的字段关联起来)
     */
    public static <T> List<T> readExcelContent(InputStream inputStream, Map<Integer,String> fieldNames ,Class<T> c,String xlsType) {
        Workbook wb= null;
        List<T> list=new ArrayList<T>();
        try {
            if("xlsx".equals(xlsType)) {
                wb = new XSSFWorkbook(inputStream);
            }
            if("xls".equals(xlsType)) {
                wb = new XSSFWorkbook(inputStream);
            }

        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        Sheet sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        Row row = sheet.getRow(0);
        //获取总列数
        int colNum = row.getPhysicalNumberOfCells();
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            T t = null;
            try {
                t = c.newInstance();
            } catch (InstantiationException e) {
                logger.error(e.getMessage());
            } catch (IllegalAccessException e) {
                logger.error(e.getMessage());
            }
            while (j < colNum) {
                //根据execl列的顺序获取对应javabean的字段,需要自己中map中先定义
                String fieldName=fieldNames.get(j);
                if (null !=fieldName ){
                    Cell cell = row.getCell(j);
                        try {
                            Field field=c.getDeclaredField(fieldName);
                            if(null != field && cell !=null) {
                                //获取字段的类型
                                Class type = field.getType();
                                Method m = c.getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), type);
                                //字段类型不同,取cell值的类型也不同
                                if (type.equals(Long.class)) {
                                    m.invoke(t,new Double(cell.getNumericCellValue()).longValue());
                                }else if(type.equals(Date.class) ){
                                    m.invoke(t,cell.getDateCellValue()==null?new Date():cell.getDateCellValue());
                                }else if(type.equals(java.sql.Timestamp.class)){
                                    m.invoke(t,TimeUtil.dateToTimestamp(cell.getDateCellValue()));
                                }else{
                                    if(cell.getCellType()==Cell.CELL_TYPE_STRING) {
                                        m.invoke(t, cell.getStringCellValue());
                                    }else{
                                        m.invoke(t, String.valueOf(cell.getNumericCellValue()));
                                    }
                                }
                            }
                        } catch (NoSuchMethodException e) {
                            logger.error(e.getMessage());
                        } catch (InvocationTargetException e) {
                            logger.error(e.getMessage());
                        } catch (IllegalAccessException e) {
                            logger.error(e.getMessage());
                        } catch (NoSuchFieldException e) {
                            logger.error(e.getMessage());
                        }
                }
                j++;
            }
            list.add(t);
        }
        return list;
    }
}
